/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.friendforsale.command;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import opensocial.apps.common.Message;
import opensocial.apps.friendforsale.Config;
import opensocial.apps.friendforsale.Tools;
import opensocial.apps.friendforsale.model.Activity;
import opensocial.apps.friendforsale.model.ActivityType;

import org.apache.log4j.Logger;

public class SimpleFawnCommand extends DostuffCommand {
  public static final Logger LOGGER = Logger.getLogger(SimpleFawnCommand.class);

  private Integer lock;

  public Integer getLock() {
    if (lock == null) {
      lock = config.getInteger(Config.FAWN_INTERVAL, 12);
    }
    return lock;
  }

  public void setLock(Integer lock) {
    this.lock = lock;
  }

  @Override
  public boolean execute() throws Exception {
    Map<String, Object> params = new HashMap<String, Object>();

    if (!Tools.isSlave(target, viewer)) {
      output(new Message(MessageId.NOT_YOUR_SLAVE, null));
      LOGGER.info("try to fawn master not viewer`s :" + viewer.getUserId()
          + " target:" + target.getUserId());
      return END;
    }

    Activity last = persist.getLastActivity(viewer, target, ActivityType.FAWN);
    Date now = new Date();
    if (last != null && last.getUntil() != 0) {
      if (now.getTime() < last.getUntil()) {
        params.put("activity", last.getCommand());
        params.put("until", last.getUntil());
        output(new Message(MessageId.SLAVE_AT_WORK, params));
        LOGGER.info("slave at work:" + last.getCommand());
        return END;
      }
    }

    Activity activity = this.newActivity(ActivityType.FAWN);
    activity.setUntil(Tools.lock(now, getLock()));

    persist.save(viewer);
    persist.save(target);
    persist.save(activity);

    LOGGER.info("reward action success.");

    this.hasError(false);
    params.put("viewer", viewer);
    params.put("target", target);
    output(new Message(getMessageId(), params));
    return NEXT;
  }

}
